from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from app.models.models import SysUser
from app.utils.auth import get_current_active_user
from app.schemas.schemas import MonitorResponse
from app.utils.system_monitor import SystemMonitor
import psutil
import datetime

router = APIRouter()
templates = Jinja2Templates(directory="app/templates")
monitor = SystemMonitor()

# 页面路由 - 返回监控页面
@router.get("/monitor", response_class=HTMLResponse)
async def get_monitor_page(request: Request):
    return templates.TemplateResponse("monitor.html", {"request": request})

# API路由 - 获取系统监控数据
@router.get("/api/monitor", response_model=MonitorResponse)
async def get_monitor_data(current_user: SysUser = Depends(get_current_active_user)):
    """获取系统监控数据"""
    # 检查是否为管理员
    if current_user.is_admin == 0:
        raise HTTPException(status_code=403, detail="无权访问")
    
    # 获取监控数据
    raw_data = monitor.get_all_info()
    
    # 处理CPU和内存历史数据
    current_time = datetime.datetime.now()
    cpu_history = []
    memory_history = []
    
    # 转换CPU历史数据
    for i, value in enumerate(raw_data['resource_usage'].get('cpu_history', [])):
        timestamp = (current_time - datetime.timedelta(seconds=(180-i)*5)).strftime("%H:%M:%S")
        cpu_history.append({"timestamp": timestamp, "value": value})
    
    # 转换内存历史数据
    for i, value in enumerate(raw_data['resource_usage'].get('memory_history', [])):
        timestamp = (current_time - datetime.timedelta(seconds=(180-i)*5)).strftime("%H:%M:%S")
        memory_history.append({"timestamp": timestamp, "value": value})
    
    # 构造符合MonitorResponse格式的响应数据
    response_data = {
        "system_info": raw_data['system_info'],
        "resource_usage": {
            "cpu_percent": raw_data['resource_usage']['cpu_percent'],
            "cpu_count": psutil.cpu_count(),
            "memory_total": raw_data['resource_usage']['memory_total'],
            "memory_used": raw_data['resource_usage']['memory_used'],
            "memory_percent": raw_data['resource_usage']['memory_percent'],
            "disk_total": raw_data['resource_usage']['disk_total'],
            "disk_used": raw_data['resource_usage']['disk_used'],
            "disk_percent": raw_data['resource_usage']['disk_percent']
        },
        "cpu_history": cpu_history,
        "memory_history": memory_history
    }
    
    return response_data 